package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

//连接数据库的工具类
public class DBUtil {

	private static DataSource dataSource;

	//通过静态代码块
	static {
		try {
			//1. 创建Properties对象
			Properties properties = new Properties();
			//2. 将配置文件转换成字节输入流
			InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
			//3. 使用properties对象加载is
			properties.load(is);
			//druid底层是使用的工厂设计模式，去加载配置文件，创建DruidDataSource对象
			dataSource =DruidDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Connection getDataSource() throws SQLException {
		return dataSource.getConnection();//返回dataSource
	}
	public static void main(String[] args) throws SQLException {
		Connection conn = (Connection) DBUtil.getDataSource();
		if (conn!=null) {
			System.out.println(conn.toString());
			System.out.println("数据库连接成功");
		}
	}

}


